import axios from 'axios'
// import router from '../router/index'
import { Loading, Notification } from 'element-ui'
import { sendMsgEvent, EVENT_TYPE } from '@utility/eventBus'
import { debounce } from '@utility/utility'

axios.defaults.headers.post['Content-Type'] = 'application/json'
axios.defaults.timeout = 60000

let loading
// 内存中正在请求的数量
let loadingNum = 0

function startLoading() {
  if (loadingNum === 0) {
    loading = Loading.service({
      lock: true,
      text: '加载中...',
      background: 'rgba(255,255,255,0.5)',
    })
  }
  // 请求数量加1
  loadingNum++
}

function endLoading() {
  // 请求数量减1
  if (loadingNum > 0) {
    loadingNum--
  }
  if (loadingNum <= 0) {
    loading && loading.close()
  }
}

const showErrMsg = debounce(err => {
  showErrNotification(err)
}, 1200)

function randomString(len) {
  len = len || 32
  const charsAll =
    'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678' /** **默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  const maxPos = charsAll.length
  let pwd = ''
  for (let i = 0; i < len; i++) {
    pwd += charsAll.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}

// 请求数据拦截器
axios.interceptors.request.use(
  config => {
    const ctimestamp = parseInt(Date.now() / 1000) // 时间戳
    const cnonce = randomString(6)
    let papams = 'params'
    if (
      (config.data || config.params) &&
      (config.data || config.params) instanceof Object &&
      Object.keys(config.data || config.params).length > 0
    ) {
      papams = Object.values(config.data || config.params)[0] || ''
    }
    const sm3 = require('sm-crypto').sm3
    const cData = `${papams}-POST-${ctimestamp}-${cnonce}`
    const csign = sm3(cData)
    config.headers.ctimestamp = ctimestamp
    config.headers.cnonce = cnonce
    config.headers.csign = csign
    const appCode = localStorage.PSKH_USERINFO
      ? JSON.parse(localStorage.PSKH_USERINFO).appCode
      : localStorage.system_userInfo
      ? JSON.parse(localStorage.system_userInfo).appCode // eslint-disable-line
      : config.headers.appCodeSelf // eslint-disable-line
      ? config.headers.appCodeSelf // eslint-disable-line
      : '' // eslint-disable-line
    config.headers.appCode = appCode
    config.headers.userId = localStorage.pskh_userId
    config.headers.tenantId = localStorage.pskh_tenantId
    config.headers.token = localStorage.token
    config.headers.userName = encodeURIComponent(sessionStorage.userName)
    if (localStorage.pskh_userId === 'admin') {
      config.headers.organId = ''
    } else {
      config.headers.organId = localStorage.PSKH_USERINFO
        ? JSON.parse(localStorage.PSKH_USERINFO).loginPostInfo.orgId
        : ''
    }

    config.headers.type = 2

    if (!config.headers.hideLoading) {
      startLoading()
    }
    // 处理post formdata传参问题
    if (config.method === 'post' && config.headers['content-Type'] === 'application/x-www-form-urlencoded') {
      let data = ''
      for (const item in config.data) {
        if (config.data[item]) {
          data += encodeURIComponent(item) + '=' + encodeURIComponent(config.data[item]) + '&'
        }
      }
      config.data = data.slice(0, data.length - 1)
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// 接收响应拦截器
axios.interceptors.response.use(
  response => {
    endLoading()
    if (response.headers['content-type'].includes('application/msword')) {
      return response
    }
    if (response.headers['content-type'].includes('download') || response.headers['content-type'].includes('stream')) {
      if (response.status !== 200) {
        showErrMsg(response.data)
      }
    } else if (!(response.data.status === 200 || response.data.code === 0)) {
      showErrMsg(response.data)
      if (response.data.status === 401) {
        sendMsgEvent(EVENT_TYPE.goLogin)
        localStorage.clear()
        sessionStorage.clear()
      }
    }

    return response
  },
  err => {
    endLoading()
    showErrMsg(err.response)
    return Promise.reject(err)
  }
)

export const GET = async (url, params) => {
  const res = await axios.get(url, {
    params,
  })
  // if (res.headers['content-type'].includes('download') || res.headers['content-type'].includes('stream')) {
  //   return res
  // }
  return res.data
}

export const POST = async (url, params, config = {}) => {
  const res = await axios.post(url, params || {}, {
    ...config,
  })
  if (res.headers['content-type'].includes('download')) {
    return res
  }
  return res.data
}

function showErrNotification(err) {
  let errMsg = err && (err.msg || err.message)
  if (!errMsg && err && err.status) {
    switch (err.status) {
      case 400:
        errMsg = '请求错误(400)'
        break
      case 401:
        errMsg = '请重新登录(401)'
        break
      case 403:
        errMsg = '拒绝访问(403)'
        break
      case 404:
        errMsg = '请求出错(404)'
        break
      case 408:
        errMsg = '请求超时(408)'
        break
      case 500:
        errMsg = '服务器错误(500)'
        break
      case 501:
        errMsg = '服务未实现(501)'
        break
      case 502:
        errMsg = '网络错误(502)'
        break
      case 503:
        errMsg = '服务不可用(503)'
        break
      case 504:
        errMsg = '网络超时(504)'
        break
      case 505:
        errMsg = 'HTTP版本不受支持(505)'
        break
      default:
        errMsg = `请求出错(${err.status})!`
    }
  }
  Notification.error({
    title: '错误',
    message: errMsg || '服务器错误',
    duration: 2000,
  })
}
